package org.tloss.web.editor.form.editors;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.tloss.web.editor.model.Form;
import org.tloss.web.editor.model.FormField;
import org.tloss.web.editor.utils.Constants;

public class FormFieldList implements IWorkbenchAdapter, IAdaptable {

	private Form form;
	private IResourceChangeListener dirtyListener;

	public FormFieldList(Form form, IResourceChangeListener dirtyListener) {
		this.form = form;
		this.dirtyListener = dirtyListener;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object getAdapter(Class adapter) {
		if (adapter == IWorkbenchAdapter.class)
			return this;

		return null;
	}

	@Override
	public Object[] getChildren(Object arg0) {
		if (form != null) {
			List<FormField> fields = form.getFormFields();
			if (fields != null) {
				List<FormFieldElement> elements = new ArrayList<FormFieldElement>();
				FormFieldElement element;
				for (int i = 0; i < fields.size(); i++) {
					element = new FormFieldElement(fields.get(i), dirtyListener);
					elements.add(element);
				}
				if (elements.size() > 0) {
					return elements.toArray();
				}
			}
		}
		return Constants.EMPTY_ARRAY;
	}

	@Override
	public ImageDescriptor getImageDescriptor(Object arg0) {
		return null;
	}

	@Override
	public String getLabel(Object o) {
		return o == null ? "" : o.toString();
	}

	@Override
	public Object getParent(Object arg0) {
		return null;
	}

}
